package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.domain.Category;
import com.itheima.domain.Setmeal;
import com.itheima.dto.SetMealDto;
import com.itheima.service.CatgoryService;
import com.itheima.service.SetMealService;
import com.itheima.tool.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    SetMealService service;

    @Autowired
    CatgoryService cateService;

    @GetMapping("/page")
    public R getAllSetMealByPage(Integer page, Integer pageSize, String name){
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetMealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Setmeal::getName,name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        service.page(pageInfo,queryWrapper);


        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();

        List<SetMealDto> list = records.stream().map((item) -> {
            SetMealDto setmealDto = new SetMealDto();

            BeanUtils.copyProperties(item,setmealDto);

            Long categoryId = item.getCategoryId();

            Category category = cateService.getById(categoryId);
            if(category != null){

                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    @PostMapping
    public R save(@RequestBody SetMealDto dto){

        service.savewithDish(dto);

        return R.success();
    }

    @DeleteMapping
    public R del(@RequestParam List<Long> ids){
        service.removeWithDish(ids);
        return R.success();
    }
}
